package edu.ajou.scw;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

/**
 * Servlet implementation class Action
 */
@WebServlet("/Action")
public class ActionProcessor extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ActionProcessor() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		PushSender sender = new PushSender();
		
		String team_id = (String)request.getParameter("team_id");
		String actor = (String)request.getParameter("actor");
		String act = (String)request.getParameter("action");
		
		Log.d(actor, team_id, "Action Received from team " + team_id + " by " + actor);
		
		try {
			JSONParser parser = new JSONParser();
			JSONObject obj = (JSONObject)parser.parse(act);
			obj.put("timestamp", System.currentTimeMillis());
			act = obj.toJSONString();
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Team team = Team.Load(team_id);
		
		if (team != null)
		{
			ArrayList<String> members = team.getMembers();

			for (int i=0; i<members.size(); i++)
			{
				String target = members.get(i);
				if (!target.equals(actor))
					sender.sendPush(members.get(i), "action", act);
			}
		}
	}

}
